<template>
  <div v-loading.fullscreen.lock="loading">
    <div>
      <div>
        <div style="padding: 12px 0 0 12px">
          <el-button
            icon="el-icon-s-home"
            size="mini"
            type="primary"
            round
            plain
            @click="goBack"
          >
            返回</el-button
          >
          <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
            round
            plain
            @click="onSubmit"
          >
            提交修改</el-button
          >
          <el-button
            icon="el-icon-document-copy"
            size="mini"
            type="primary"
            round
            plain
            @click="changeMetaDataName"
          >
            更该调查表</el-button
          >
          <el-button
          icon="el-icon-refresh-right"
            size="mini"
            type="primary"
            round
            plain
            @click="setValue"
            >
            重设
          </el-button>
        </div>
      </div>
    </div>
    <el-tabs
      :tab-position="tabPosition"
      style="margin: 0; padding-top: 20px; padding-left: 20px"
    >
      <el-tab-pane label="记录信息">
        <form-create
          v-model="resp.fapi"
          :value.sync="resp.value"
          :option="option"
          :rule="resp.rule"
        />
      </el-tab-pane>
      <el-tab-pane v-for="item in forms" :key="item.i">
        <div slot="label" style="display: flex; justify-content: center">
          <img
            v-if="!!item.icon"
            :src="item.icon[0]"
            height="30px"
            class="image"
          />
          <div style="line-height: 30px; height: 30px">
            {{ item.title }}
          </div>
        </div>

        <form-create
          v-model="item.fapi"
          :value.sync="item.value"
          :option="option"
          :rule="item.rule"
        />
      </el-tab-pane>

      <el-tab-pane label="操作记录">
        <el-timeline>
          <el-timeline-item
            v-for="op in operationList"
            :key="op.time"
            :timestamp="op.time"
            placement="top"
          >
            <el-card>
              <p>操作人： {{ op.personName + " : " + op.personId }}</p>
              <p>
                操作记录：<el-tag>
                  {{ op.type }}
                </el-tag>
              </p>
              <p>备注信息：{{ op.msg }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-tab-pane>
    </el-tabs>
    <!-- <el-button @click="tabPosition = 'top'" size="mini" icon="el-icon-top"> </el-button> -->
    <el-dialog title="更改调查模板" :visible.sync="dialogVisible" width="500px">
      模板名称：
      <metadata-select v-model="selectedTemp" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleMetaDataNameOK"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fileDownload,
  getData,
  getResp,
  logout,
  postJSON,
  putJSON,
} from "@/utils/http";
import { mapGetters } from "vuex";
import { getConfigData, URL_MAP } from "@/config/config";
import { generateID, loadJSON, parseConfig, writeJSON } from "@/utils/utils";

// logout
export default {
  data() {
    return {
      tabPosition: "top",
      loading: false,
      dialogVisible: false,
      selectedTemp: "",
      forms: [],
      operationList: [],
      resp: {
        fapi: {},

        rule: [],

        value: {},
      },
      raw_data:{},
      all_value: {},
      option: {
        form: {
          labelPosition: "right",
          size: "mini",
          labelWidth: "200px",
          hideRequiredAsterisk: false,
          showMessage: true,
          inlineMessage: true,
        },
        row: {
          gutter: 12,
          type: "flex",
          align: "middle",
          justify: "start",
          tag: "div",
        },
        submitBtn: false,
      },
    };
  },
  computed: {
    ...mapGetters(["selectRecord", "token", "isLogin", "isAdmin", "userid"]),
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    getAllValue() {
      const v = {};
      this.forms.forEach((f) => {
        Object.assign(v, f.fapi.formData());
      });
      return v;
    },
    onSubmitBack() {
      this.onSubmit().finally(this.goBack);
    },
    changeMetaDataName() {
      this.dialogVisible = true;
    },
    handleMetaDataNameOK() {
      this.loading = true;
      this.dialogVisible = false;
      putJSON(URL_MAP.RECORD_META, {
        uuid: this.selectRecord,
        metaDataName: this.selectedTemp,
      })
        .then((res) => {
          if (res.code === 0) {
            this.$message.success("修改成功！");
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((e) => {
          console.log(e);
          this.$message.error("修改失败！");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async onSubmit() {
      try {
        // 提交流调记录
        // console.log(this.all_value)
        const all_value = this.getAllValue();
        const record = this.resp.value;
        record.values = all_value;
        console.log(record)
        // record.metaDataName = this.selectedTemp;

        let data = await putJSON(URL_MAP.PUT_LOG, record);
        if (data.code === 0) {
          this.$message.success("修改成功！");
          return true;
        } else {
          this.$message.error(data.msg);
          return false;
        }
      } catch (e) {
        console.log(e);
        this.$message.error("修改记录失败！");
      }
    },
    startSurveyTask() {
      this.setDisable(false);
    },
    fetch() {
      let tempForm = [];
      this.loading = true;
      getData(URL_MAP.METADATA, {
        name: this.selectedTemp,
      })
        .then((data) => {
          if (data.code === 0) {
            this.$notify.success("获取数据成功！");

            let form = data.data.form.subforms;
            // parseConfig
            form.forEach((v) => {
              v.fapi = {};
              v.value = {};
            });

            let downs = [];

            form.forEach((v) => {
              let subdowns = [];
              v.rule.forEach((r) => {
                subdowns.push(fileDownload.get(r));
              });
              downs.push(Promise.all(subdowns));
            });
            tempForm = form;
            return Promise.all(downs);
          } else {
            this.$notify.error(data.msg);
            return Promise.all([]);
          }
        })
        .then((data) => {
          tempForm.forEach((v, i) => {
            let rule = [];
            data[i].forEach((r) => {
              rule = rule.concat(
                parseConfig(r.data, {
                  token: this.token,
                  upload_url: "/backend/upload/",
                }, this, true)
              );
            });
            v.rule = rule;
          });
          this.forms = tempForm;
        })
        .catch((e) => {
          console.log(e);
          this.$notify.error("获取数据失败！");
        })
        .finally(() => {
          this.loading = false;
        });

      setTimeout(this.setValue, 0);
    },
    setValue() {
      this.forms.forEach((f) => {
        f.fapi.setValue(this.raw_data.values);
      });
    },
    setDisable(s) {
      this.forms.forEach((f) => {
        f.fapi.disabled(s);
      });
    },
  },
  async mounted() {
    this.loading = true;
    try {
      let data = await getData(URL_MAP.LOG_DETAIL, {
        uuid: this.selectRecord,
      });
      if (data.code === 0) {
        data = data.data;
        console.log(data);
        this.raw_data = data
        this.$message.success("获取数据成功！");

        this.all_value = data.values;
        this.selectedTemp = data.template;
        this.operationList = data.operationInfoList;
        let rule = getConfigData('resp_read_info')
        rule = parseConfig(rule)
        this.resp.rule = rule;
        this.resp.value.idNumber = data.idNumber;
        this.resp.value.uuid = data.uuid;
        this.fetch();
      } else {
        this.$message.error(data.msg);
      }
    } catch (e) {
      console.log(e);
      this.$message.error("获取数据失败！");
    } finally {
      this.loading = false;
    }
    setTimeout(() => {
      for(let k in this.resp.value) {
          this.resp.value[k] = this.raw_data[k]
      }
      this.resp.fapi.setValue(this.resp.value);
    }, 0);
  },
};
</script>

<style>
.el-tabs__content {
  padding-right: 94px;
  /* overflow-y: scroll !important; */
}
.el-row--flex {
  flex-wrap: wrap;
}
</style>